import {Button, Collapse, Form, Input, Upload, message} from 'antd'
import moment from 'moment'
import React, {useState, useEffect, useRef} from 'react'
import {connect, history, useModel} from 'umi'
import type {UploadFile} from 'antd/es/upload/interface'
import {QuestionCircleFilled} from '@ant-design/icons'
import {getPublicDownloadUrl, uploadFileUrl} from '@/service/common/upload'
import styles from './index.less'
import {
	checkStatus,
	editSupplierArchives,
	getDisableData,
	getSelectContractList,
} from '@/service/supplier/supplierArchives'
import Modal from '@/components/Modal'
import Examine from '@/components/Examine'
import {
	completeTask,
	deleteProcessInstance,
	getOperatelogList,
	processRecordSave,
} from '@/service/common'

const {Panel} = Collapse
const {TextArea} = Input

const add = (props: any) => {
	const {query} = props.location
	const [type, setType] = useState<string>()
	const [form] = Form.useForm()
	const examineRef = useRef<any>(null)
	const [fileList, setFileList] = useState<UploadFile[]>([])
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [isExamineModalOpen, setIsExamineModalOpen] = useState(false)
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [examineType, setExamineType] = useState<string>('')
	const [btnLoading, setBtnLoading] = useState(false)
	const [detailsData, setDetailsData] = useState<any>({})
	const [disableData, setDisableData] = useState<any>({})
	const [contractStatus, setContractStatus] = useState<boolean>(false)

	/** 获取准出记录 */
	const getOperatelogListFun = () => {
		getOperatelogList({
			current: 1,
			size: 10,
			businessType: 24,
			businessId: query?.id,
		})
			.then((res: any) => {
				if (res?.success) {
					setDisableData({
						num: res?.data?.total,
						date: res?.data?.records?.[0]?.logTime,
					})
				} else {
					setDisableData({})
				}
			})
			.catch((err) => {
				setDisableData({})
				message.error(err)
			})
	}
	// 根据路由判断当前页面状态
	useEffect(() => {
		const hrefs = window.location.href
		if (hrefs.includes('enable')) {
			getOperatelogListFun()
			setType('enable')
		} else if (hrefs.includes('disable')) {
			setType('disable')
		} else {
			setType('examine')
		}
		if (!hrefs.includes('examine')) {
			form.setFieldsValue({
				disablePersonName: props?.user?.userName,
				disableDate: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
			})
		}
	}, [])

	useEffect(() => {
		if (query?.id && type === 'examine') {
			getDisableData({supplierId: query?.id})
				.then((res: any) => {
					if (res?.success) {
						setDetailsData(res?.data)
						const url = res?.data?.disableFileUrl?.split(',')
						if (url?.length) {
							getPublicDownloadUrl(url)
								.then((result: any) => {
									if (result?.success) {
										const urlData = result?.data?.map(
											(item: {
												id: number
												filename: any
												url: any
											}) => ({
												uid: item?.id,
												name: item?.filename,
												url: item?.url,
											}),
										)
										form.setFieldsValue({
											...res?.data,
											disableFileUrl: urlData,
										})
									}
								})
								.catch((err: any) => {
									message.error(err)
								})
						}
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}
		if (query?.id) {
			getSelectContractList({
				current: 1,
				size: 10,
				supplierId: query?.id,
				contractExpire: 1,
			}).then((res: any) => {
				if (res?.success) {
					if (res?.data?.total > 0) {
						setContractStatus(true)
					} else {
						setContractStatus(false)
					}
				}
			})
		}
	}, [query, type])
	useEffect(() => {
		if (query?.id) {
			getSelectContractList({
				current: 1,
				size: 10,
				supplierId: query?.id,
				contractExpire: 1,
			}).then((res: any) => {
				if (res?.success) {
					if (res?.data?.total > 0) {
						setContractStatus(true)
					} else {
						setContractStatus(false)
					}
				}
			})
		}
	}, [query])

	const customizeHeader = (value: string) => (
		<div>
			<div className={styles.tip} />
			{value}
		</div>
	)
	const submit = async () => {
		const values = await form.validateFields()
		const disableFileUrl = fileList?.map(
			(item) => item?.response?.data?.id || item?.uid,
		)
		if (values) {
			const newData = {
				...values,
				disablePersonId: props?.user?.userId,
				disableFileUrl: disableFileUrl.toString(),
				status: query?.status,
			}
			editSupplierArchives({...newData, id: query.id})
				.then((res: any) => {
					if (res.success) {
						message.success(res.msg)
						history.goBack()
					}
					setBtnLoading(false)
				})
				.catch((err: any) => {
					message.error(err)
					setBtnLoading(false)
				})
		}
	}

	const normFile = (e: any) => {
		if (Array.isArray(e)) {
			return e
		}
		return e?.fileList
	}

	const uploadProps = {
		action: uploadFileUrl,
		name: fileName,
		data: {
			modelName: 'spArchives',
			targetAttr: 1,
		},
		onChange(info: any) {
			setFileList(info?.fileList)
			if (info.file.status === 'done') {
				setFileList(info?.fileList)
			}
		},
		fileList,
	}

	/** 审核 */
	const onCompleteTask = async () => {
		setBtnLoading(true)
		const examineData = await examineRef.current.getData()
		const userId = props?.user?.userId
		let request
		if (examineType === '拒绝') {
			request = deleteProcessInstance({
				processId: query?.processInstanceId,
				reason: JSON.stringify({
					url: examineData?.url,
					message: examineData?.message,
					userId: userId.toString(),
				}),
			})
		} else {
			request = completeTask({
				reviewerId: userId.toString(),
				processInstanceId: query?.processInstanceId,
				pass: examineType === '同意' ? 1 : 2,
				...examineData,
			})
		}
		request
			.then(async (res: any) => {
				if (res?.success) {
					if (examineType === '拒绝') {
						processRecordSave({
							bizType: 8,
							bizNo: query?.id,
							processId: query?.processInstanceId,
						})
					}
					if (
						res?.data?.processStatus === 2 &&
						examineType === '同意'
					) {
						// 审核流程结束修改数据状态
						checkStatus({
							status: query?.status === 1 ? 2 : 1,
							id: query.id,
							disableFileUrl: detailsData?.disableFileUrl,
							disableReason: detailsData?.disableReason,
						})
							.then((result: any) => {
								if (result.success) {
									message.success(result.msg)
									history.goBack()
								}
							})
							.catch((err: any) => {
								message.error(err)
							})
					} else {
						history.goBack()
						setBtnLoading(false)
					}
				} else {
					setBtnLoading(false)
				}
			})
			.catch((err) => {
				message.error(err)
				setBtnLoading(false)
			})
	}
	return (
		<div className={styles.archivesAdd}>
			<div className={styles.content}>
				{type === 'examine' && query?.processInstanceId ? (
					<Examine
						ref={examineRef}
						examineType={query?.examine}
						orgId={props?.user?.orgId}
						processInstanceId={query?.processInstanceId}
						bizType={8}
						bizNo={query?.id}
					/>
				) : (
					''
				)}
				<Collapse
					defaultActiveKey={['1']}
					ghost
					expandIconPosition="end">
					<Panel
						header={customizeHeader(
							query?.status === 1 ? '准出记录' : '准入记录',
						)}
						key="1">
						<p className={styles.tips}>
							<QuestionCircleFilled />{' '}
							{type === 'enable'
								? `确定要启用该供应商吗?该供应商一共操作了${disableData?.num}次禁用，最近一次${disableData?.date}对该供应商进了禁用，可在详情查看更多禁用原因?`
								: `确定要禁用该供应商吗? ${
										contractStatus
											? '该供应商还有合同未到期，'
											: ''
								  }禁用后不影响当前供应商提付款申请单，但不可新建与该供应商关联的采购-招投标-修改评级，禁用后可重新启用`}
						</p>
						<Form
							form={form}
							name="basic"
							layout="horizontal"
							labelCol={{flex: '140px'}}
							labelAlign="right"
							labelWrap
							autoComplete="off"
							disabled={type === 'examine'}>
							<Form.Item
								label={
									query?.status === 1
										? '禁用原因'
										: '启用原因'
								}
								name="disableReason"
								rules={[{required: true}]}
								colon>
								<TextArea
									maxLength={200}
									placeholder="请输入（最多200个字）"
									autoSize={{
										minRows: type === 'examine' ? 1 : 3,
										maxRows: 6,
									}}
								/>
							</Form.Item>
							<Form.Item
								name="disableFileUrl"
								label="附件上传"
								valuePropName="fileList"
								getValueFromEvent={normFile}
								rules={[
									{required: true, message: '请上传附件'},
								]}
								className={styles.fileUpload}>
								<Upload {...uploadProps}>
									{fileList.length >= 5 ||
									type === 'examine' ? null : (
										<Button className={styles.uploadBtn}>
											请选择文件
										</Button>
									)}
								</Upload>
							</Form.Item>
							<div className={styles.uploadTip}>
								附件说明：支持格式rar .zip .doc .docx .pdf .jpg
								.png .xlsx
								xls等,每个文件最大为200MB,最多可上传5个文件
							</div>
							<Form.Item
								label={
									query?.status === 1 ? '禁用人' : '启用人'
								}
								name="disablePersonName"
								rules={[{required: true}]}>
								<Input placeholder="请输入" disabled />
							</Form.Item>
							<Form.Item
								label={
									query?.status === 1
										? '禁用日期'
										: '启用日期'
								}
								name="disableDate"
								rules={[{required: true}]}>
								<Input placeholder="请输入" disabled />
							</Form.Item>
						</Form>
					</Panel>
				</Collapse>
				<div className={styles.wrap}>
					{query?.examine === 'true' ? (
						<>
							<Button
								type="primary"
								htmlType="submit"
								onClick={() => {
									setExamineType('同意')
									setIsExamineModalOpen(true)
								}}>
								同意
							</Button>
							<Button
								onClick={() => {
									setExamineType('驳回')
									setIsExamineModalOpen(true)
								}}>
								驳回
							</Button>
							<Button
								onClick={() => {
									setExamineType('拒绝')
									setIsExamineModalOpen(true)
								}}>
								拒绝
							</Button>
						</>
					) : (
						<Button
							type="primary"
							htmlType="submit"
							onClick={async () => {
								const values = await form.validateFields()
								if (values) {
									setIsModalOpen(true)
								}
							}}>
							提交
						</Button>
					)}
					<Button
						onClick={() => {
							history.go(-1)
						}}>
						返回
					</Button>
				</div>
			</div>
			<Modal
				text="确定要提交吗？请仔细核对所填信息"
				loading={btnLoading}
				onSubmit={submit}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
			<Modal
				text={`确定要${examineType}吗？请仔细核对所填信息`}
				loading={btnLoading}
				onSubmit={onCompleteTask}
				isModalOpen={isExamineModalOpen}
				setIsModalOpen={setIsExamineModalOpen}
			/>
		</div>
	)
}

export default connect(({user}: any) => ({user}))(add)
